import { login, getUserInfo, getUserDetailById } from '@/api/user'

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  logout(state) {
    localStorage.removeItem('token')
    state.token = ''
    state.userInfo = {}
  }
}
const actions = {
  async login(context, payload) {
    const res = await login(payload)
    // console.log(res.data.data)
    context.commit('setToken', res)
    // 主动监听超时，在点击登录的时候把时间记录下来
    const now = Date.now()
    localStorage.setItem('time', now)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    const detail = await getUserDetailById(res.userId)
    const userInfo = { ...res, ...detail }
    context.commit('setUserInfo', userInfo)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

